import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

import cmpe273.classproject.server.dto.MovieResponse;
import cmpe273.classproject.server.model.Movie;
import cmpe273.classproject.server.service.MovieServiceImplProxy;

public class NewMovie extends javax.swing.JFrame {
	MovieServiceImplProxy proxy = new MovieServiceImplProxy();
    /** Creates new form NewMovie */
    public NewMovie() {
        initComponents();
    }
    
    public NewMovie(AllMovies ui) {
        allMovies = ui;
        initComponents();        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        movieName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        banner = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        releaseDate = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        rentAmount = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        availCopies = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel1.setText("Movie");

        jLabel2.setText("Movie Name");

        jLabel3.setText("Banner");

        jLabel4.setText("Release Date");

        releaseDate.setText("yyyy-mm-dd");

        jLabel6.setText("Rent Amount");

        jLabel7.setText("$");

        jLabel8.setText("Total copies");

        jButton1.setText("Save");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancel");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel5.setText("Category");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel6))
                                .addGap(26, 26, 26)
                                .addComponent(jLabel7))
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(banner)
                            .addComponent(movieName, javax.swing.GroupLayout.DEFAULT_SIZE, 228, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(rentAmount, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(availCopies))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addGap(18, 18, 18)
                                .addComponent(jButton2))
                            .addComponent(jTextField1)
                            .addComponent(releaseDate, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE))))
                .addContainerGap(50, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(movieName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(banner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(releaseDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel6)
                        .addComponent(rentAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel7))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel8)
                        .addComponent(availCopies, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(24, Short.MAX_VALUE))
        );
        this.setLocationRelativeTo(null);
        pack();
    }// </editor-fold>

    public AllMovies allMovies = null; 
    public boolean bNew = true;
    public String sMovieName = "";
    public String sBanner = "";
    public String sReleaseDate = "";
    public String sGenere ="";
    public String sRentAmount = "";
    public String sAvailCopies = "";
    public String sTotalCopies = "";
    public int iMovieId;
    
    public void setEditValues()
    {
        movieName.setText(sMovieName);
        banner.setText(sBanner);
        releaseDate.setText(sReleaseDate);
        jTextField1.setText(sGenere);
        rentAmount.setText(sRentAmount);
        availCopies.setText(sAvailCopies);       
        
    }
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
    	
    	Pattern pintegerchecker = Pattern.compile("^[0-9]{1,3}$");
    	Matcher m1 = pintegerchecker.matcher(availCopies.getText());
    	boolean copieschecker = m1.matches();
    	Matcher m2 = pintegerchecker.matcher(rentAmount.getText());
    	boolean amountchecker = m2.matches();
    	
    	
    	 if((movieName.getText().length()<3)||( movieName.getText().length()>15)||(movieName.getText()=="")){ 
       		JOptionPane.showMessageDialog(null,"Invalid Movie Name");
       		}
    	 else if((banner.getText().length()<3)||( banner.getText().length()>15)||(banner.getText()=="")){ 
   		JOptionPane.showMessageDialog(null,"Invalid Banner");
   		}
   		
   		else if((copieschecker==false)||(availCopies.getText()=="")){ 
   		JOptionPane.showMessageDialog(null,"Invalid Number of copies");
   		}
   		else if((amountchecker==false)||(rentAmount.getText()=="")){ 
   	  		JOptionPane.showMessageDialog(null,"Invalid Amount");
   	  		}
   		else if ((jTextField1.getText()=="")||(jTextField1.getText().length()<3)|| (jTextField1.getText().length()>15)){
   	  		JOptionPane.showMessageDialog(null,"Invalid Category");
   		}
   		
   		 
   		else{
    	
            Movie m = new Movie();
            m.setMovieBanner(banner.getText());
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date d = null;
			try {
				d = df.parse(releaseDate.getText());
			} catch (ParseException e1) {
				JOptionPane.showMessageDialog(this, "Date is malformed, try again.");
				return;
			}
            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
            m.setReleaseDate(cal);
            m.setMovieName(movieName.getText());
            m.setMovieCategory(jTextField1.getText());
            m.setAvailableCopy(Integer.parseInt(availCopies.getText()));
            m.setTotalCopies(Integer.parseInt(availCopies.getText()));
            m.setRentAmount(Integer.parseInt(rentAmount.getText()));
            try {
            	MovieResponse mr;
            	if (bNew)
            	{
            		mr = proxy.createMovie(m);
            	}
            	else
            	{
            		m.setMovieId(iMovieId);
            		mr = proxy.updateMovie(m);
            	}
    			System.out.println(mr.getError());
    			if(mr.getError() != 0) {
    				JOptionPane.showMessageDialog(this, mr.getErrorMessage());
    				return;
    			}
    			else
    			{
    				if(bNew)
    	    			JOptionPane.showMessageDialog(this, "Movie " + m.getMovieName() + " was created.");
    	    		else
    	    			JOptionPane.showMessageDialog(this, "Movie " + m.getMovieName() + " was updated.");
    				
    				allMovies.dispose();
    				allMovies = null;
        		   	
        		       if (allMovies == null)
        		           {
        		    	   allMovies = new AllMovies(this);
        		           }
        		       
        		       allMovies.setVisible(true);
        		       this.setVisible(false); 
    			}
    		} catch (RemoteException e) {
    			JOptionPane.showMessageDialog(this, "Connection to backend failed.");
    			e.printStackTrace();
    		}    	
   		}
    } 
                                      

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        this.dispose();
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewMovie().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JTextField availCopies;
    private javax.swing.JTextField banner;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField movieName;
    private javax.swing.JTextField releaseDate;
    private javax.swing.JTextField rentAmount;
    // End of variables declaration

}
